package com.ygqh.baby.service.weixin.templatemessage;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.Logger;
import org.crazycake.shiro.SerializeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult;
import com.foxinmy.weixin4j.model.WeixinAccount;
import com.foxinmy.weixin4j.mp.api.TmplApi;
import com.foxinmy.weixin4j.mp.message.TemplateMessage;
import com.foxinmy.weixin4j.mp.model.TemplateMessageInfo;
import com.foxinmy.weixin4j.util.NameValue;
import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.WxMessageType;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.weixin.token.WxTokenManager;

@Component
public class WeChatTemplateMessageApi extends TemplateMessageApi {
	protected final Logger logger = Logger.getLogger(this.getClass());
	@Autowired
	private WxTokenManager tokenManager;
	@Autowired
	private RedisDao redisDao;

	@Override
	public <T extends TemplateMessage> Message sendTemplateMessage(T t, String appId, String appSecret) {
		TmplApi tmplApi = new TmplApi(tokenManager.getTokenHolder(appId, appSecret));
		JsonResult sendResult = null;
		try {
			sendResult = tmplApi.sendTmplMessage(t);
		} catch (WeixinException e) {
			logger.error("发送微信模板消息失败；openId=【" + t.getToUser() + "】【" + t.getHead() + "】" + e.getMessage());
			e.printStackTrace();
			return Message.error(e.getMessage(), null);
		}
		return Message.success(sendResult.getText(), null);
	}

	@Override
	public <T extends TemplateMessage> Message sendTemplateMessage(T t, WeixinAccount weixinAccount) {
		TmplApi tmplApi = new TmplApi(tokenManager.getTokenHolder(weixinAccount));
		JsonResult sendResult = null;
		try {
			sendResult = tmplApi.sendTmplMessage(t);
		} catch (WeixinException e) {
			logger.error("发送微信模板消息失败；openId=【" + t.getToUser() + "】【" + t.getHead() + "】" + e.getMessage());
			e.printStackTrace();
			return Message.error(e.getMessage(), null);
		}
		return Message.success(sendResult.getText(), null);
	}

	@Override
	public List<TemplateMessageInfo> getTemplateMessageList(WeixinAccount weixinAccount) {
		List<TemplateMessageInfo> allTemplates = null;
		try {
			TmplApi tmplApi = new TmplApi(tokenManager.getTokenHolder(weixinAccount));
			allTemplates = tmplApi.getAllTemplates();
		} catch (WeixinException e) {
			allTemplates = new ArrayList<TemplateMessageInfo>();
			e.printStackTrace();
		}
		return allTemplates;
	}

	@Override
	public String getTemplateMessageId(WxMessageType wxMessageType, WeixinAccount weixinAccount) {

		String key = String.format("wx_tempid_%s", weixinAccount.getId() + "_" + wxMessageType.name());
		String msgTmpId = (String) SerializeUtils.deserialize(redisDao.get(key.getBytes()));
		if (StringUtil.isEmpty(msgTmpId)) {
			List<TemplateMessageInfo> list = getTemplateMessageList(weixinAccount);
			for (TemplateMessageInfo msg : list) {
				if (wxMessageType.getTitle().equals(msg.getTitle())) {
					redisDao.set(key.getBytes(), SerializeUtils.serialize(msg.getTemplateId()));
					return msg.getTemplateId();
				}
			}
		}
		return msgTmpId;
	}

	public TemplateMessage assemblyTemplateMessage(WxMessageType wxMessageType, WeixinAccount weixinAccount, String openId, String url,
			Map<String, NameValue> contentMap) {

		String wxMsgTempId = this.getTemplateMessageId(wxMessageType, weixinAccount);
		TemplateMessage tplMessage = new TemplateMessage(openId, wxMsgTempId, "", url);
		for (Entry<String, NameValue> entry : contentMap.entrySet()) {
			String color = StringUtil.isBlank(entry.getValue().getName()) ? "#323232" : entry.getValue().getName();
			if (entry.getKey().equals("first")) {
				tplMessage.pushHead(color, entry.getValue().getValue());
			}
			tplMessage.pushItem(entry.getKey(), color, entry.getValue().getValue());
		}

		return tplMessage;
	}

	public TemplateMessage assemblyTemplateMessage(WxMessageType wxMessageType, WeixinAccount weixinAccount, String openId, String url, String head,
			String remark, String... keyword) {

		String wxMsgTempId = this.getTemplateMessageId(wxMessageType, weixinAccount);
		TemplateMessage tplMessage = new TemplateMessage(openId, wxMsgTempId, head, url);
		tplMessage.pushHead("#323232", head);
		tplMessage.pushTail(remark);
		for (int i = 0; i < keyword.length; i++) {
			tplMessage.pushItem("keyword" + (i + 1), "#323232", keyword[i]);
		}
		return tplMessage;

	}

}
